package chapter_24.udp.chat;

import java.io.*;
import java.net.*;

/**
 * Created by Administrator
 * Created time 2018/8/10 15:53.
 * 案例:聊天工具(客户端)
 */
public class ChatClient {

    public static void main(String[] args) {

        System.out.println("客户端运行...");

        Thread client = new Thread(() -> {

            try (
                    // 创建 DatagramSocket 对象,由系统分配可以使用的端口
                    DatagramSocket datagramSocket = new DatagramSocket();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in))
            ) {

                while (true) {
                    /*
                     发送数据
                     */
                    // 缓冲区
                    byte[] bytes = new byte[1024];
                    // 服务器IP地址
                    InetAddress address = InetAddress.getByName("localhost");
                    // 服务器端口
                    int port = 6666;
                    // 读取键盘输入的字符
                    String keyboardInputStr = bufferedReader.readLine();
                    // 结束聊天
                    if (keyboardInputStr.equalsIgnoreCase("bye")) {
                        break;
                    }
                    // 读取键盘输入的字节数组
                    byte[] b = keyboardInputStr.getBytes();
                    // 创建 DatagramPacket 对象
                    DatagramPacket datagramPacket = new DatagramPacket(b, b.length, address, port);
                    // 发送
                    datagramSocket.send(datagramPacket);

                    /*
                     接收数据
                     */
                    datagramPacket = new DatagramPacket(bytes, bytes.length);
                    datagramSocket.receive(datagramPacket);

                    // 接收数据长度
                    int len = datagramPacket.getLength();
                    String str = new String(bytes, 0, len);

                    // 打印接收数据
                    System.out.printf("从服务器接收的数据: [%s] \n", str);
                }

            } catch (ConnectException e) {
                System.out.println("服务器未启动!");
            } catch (SocketException e) {
                System.out.println("SocketException");
            } catch (UnknownHostException e) {
                System.out.println("UnknownHostException");
            } catch (IOException e) {
                System.out.println("IOException");
            }

            System.out.println("客户端停止!");
        });

        client.start();
    }
}